//
//  MenuController.m
//  MClient
//
//  Created by Wang Fei on 10-5-11.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "MenuController.h"
#import "MServerDAO.h"
#import "MCFunction.h"
#import "MCUIToolkit.h"
#import "MServerConfigCache.h"
#import "ModifyPasswordController.h"

#import "MCTableCell.h"
#import "MCGridMenuView.h"
#import "MCTabBarController.h"
#import "ContactController.h"

@interface MenuController (Private)
- (void) initGridMenus;
- (void) initTimer;
@end

@implementation MenuController

@synthesize menus;
@synthesize isApp;
@synthesize menuTitle;
@synthesize isShortcutMore;
#pragma mark ---- 类基本方法 ----


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[super viewDidLoad];
	// 添加左右按钮
	self.navigationController.navigationItem.hidesBackButton = NO;
		
	if (!self.userDefaults.guestDefaultLogin && !self.isShortcutMore) {
		if (isApp) {//主菜单页面
			[self leftBarButton:@"重新登录" withStyle:UIBarButtonItemStylePlain selector:@selector(logout:)];//huotianjun注销改为重新登录
			if (self.userDefaults.needModifyPassword) {
				[self rightBarButton:@"修改密码" withStyle:UIBarButtonItemStyleDone selector:@selector(modifyPassword:)];
			}
		}// else {//各子菜单页面
		//	[self rightBarButton:@"注销" withStyle:UIBarButtonItemStyleDone selector:@selector(logout:)];
		//}
	}
	
	self.tableview.backgroundColor = [UIColor clearColor];
#pragma mark---------白菜2013-2-4-----------ios6渲染兼容------------
    self.tableview.backgroundView = nil;
    
	//CGRect rc = CGRectMake(0, 0, nScreenWidth, CGRectGetMinY(self.appDelegate.shortcutsToolBar.frame));
	//self.tableview.frame = CGRectMake(0, 0, nScreenWidth, CGRectGetMinY(self.appDelegate.shortcutsToolBar.frame));
	// 显示帮助
	self.addHelpButton = YES;
	self.helpUrl = @"/iphone/help/chapter03.html";
	
	// 是九宫格菜单吗
	if ([self isGridMenu]) {
		[self initGridMenus];
		self.tableview.delegate = nil;
		self.tableview.dataSource = nil;
	}
	[self initTimer];
}

- (void) initTimer {
	return;
}

- (void) addLogoImage {
	return;
}

- (void)leftBarButton:(NSString*)aTitle withStyle:(UIBarButtonItemStyle)style selector:(SEL)sel
{
	UIBarButtonItem *button = [[UIBarButtonItem alloc]
								   initWithTitle:aTitle 
								   style:style 
								   target:self
								   action:sel];
		self.navigationItem.leftBarButtonItem = button;
		[button release]; button = nil;
}

- (bool)isGridMenu {
	return self.userDefaults.isGridMenu;
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	if (![self isGridMenu]) {
		if (self.menus != nil) {
			[menusCopy release];menusCopy = nil;
			menusCopy = [[MCUIToolkit getObjectCopy:self.menus] retain];
			[self.tableview reloadData];
		}
	}
	[self addLogoImage];
}

- (void)refreshData
{
	if ([self isGridMenu]) {
		if (self.menus != nil) {
			[menusCopy release];menusCopy = nil;
			menusCopy = [[MCUIToolkit getObjectCopy:self.menus] retain];
			MCGridMenuView *scrollView = (MCGridMenuView *)[self.clientView viewWithTag:-100];
			scrollView.menuData = menusCopy;
		}
	}
}

#pragma mark --- cuiyuguo add for toolbar ---
- (void)modifyPassword:(id)sender {
	ModifyPasswordController* controller = [[ModifyPasswordController alloc] init];
	[self.navigationController pushViewController:controller animated:YES];
	[controller release];
}

#pragma mark ---- UITableView方法 ----

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	if (self.userDefaults.contactSync && isApp) {
		return [self.menus count] + 1;
	}
	return [self.menus count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

	//static NSString *identifier = @"MenuTableCell";//[NSString stringWithFormat:@"MenuTableCell-%d-%d", indexPath.section, indexPath.row];
//	MenuCell *cell = (MenuCell*)[super tableCell:tableView withClass:[MenuCell class] withIdentifier:identifier];
	
	NSString *identifier = [NSString stringWithFormat:@"MenuTableCell-%d-%d", indexPath.section, indexPath.row];
	MenuCell *cell = (MenuCell*)[super tableCell:tableView withClass:[MenuCell class] withIdentifier:identifier];
	cell.backgroundColor = [UIColor colorWithPatternImage:self.userDefaults.skin_bgMenuCellImg];
	
	if (indexPath.row == [menusCopy count]) {
		[cell showCell:[@"   " stringByAppendingString:@"通讯录同步"]
			  withIcon:@"30.png"
				  menu:nil];
	}else {
		NSMutableDictionary *menu = [menusCopy objectAtIndex:indexPath.row];
		NSString *imageFile = [menu objectForKey:@"icon"];
		if (imageFile == nil || [imageFile length] == 0) {
			imageFile = @"0.png";
		}
		if ([menu objectForKey:@"label"]) {
			[cell showCell:[@"   " stringByAppendingString:[menu objectForKey:@"label"]]
				  withIcon:imageFile
					  menu:menu];
		}		
	}
	
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[self onMenuPressed:indexPath.row];
}

#pragma mark 九宫格菜单
-(void)initGridMenus 
{
	if (self.menus != nil) {
		[menusCopy release];menusCopy = nil;
		menusCopy = [[MCUIToolkit getObjectCopy:self.menus] retain];
	}
	MCGridMenuView* gridMenuView = [[MCGridMenuView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height)];
	gridMenuView.scrollEnabled = YES;
	gridMenuView.showsHorizontalScrollIndicator = NO;
	gridMenuView.isApp = isApp;
	gridMenuView.menuDelegate = self;
	gridMenuView.menuSelector = @selector(btnPressed:);
	gridMenuView.menuData = menusCopy;
	gridMenuView.tag = -100;
	gridMenuView.autoresizingMask = nMCViewAutoresizingMask | UIViewAutoresizingFlexibleHeight;
	
	[self.clientView addSubview:gridMenuView];
	[gridMenuView release];
}

- (void)onMenuPressed:(int)index
{
	@try {
		if (selectType) {
			[selectType release]; selectType = nil;
		}
		if (index == [self.menus count]) {
			selectType = [@"contactSync" retain];
			[[MServerDAO sharedInstance] getContactsAsync:self];
			return;
		}
		selectedIndex = 0;
		NSDictionary *menu = [self.menus objectAtIndex:index];
		NSMutableDictionary *url = [menu objectForKey:@"url"];
		NSString *actionType = @"empty_url";
		
		if ([self onSetting:menu]) {
			return;
		}
		
		NSMutableDictionary *otherParams = [NSMutableDictionary dictionary];
		[otherParams setObject:[menu objectForKey:@"id"]==nil?@"":[menu objectForKey:@"id"] forKey:@"authValue"];
		BOOL isAppMenu = [[menu objectForKey:@"app"] boolValue] || isApp;
		
		if (isAppMenu) {
			[otherParams setObject:@"app" forKey:@"authKey"];
		}else {
			[otherParams setObject:@"menu" forKey:@"authKey"];
		}
		
		if (url != nil && [url objectForKey:@"actionType"]) {
			actionType = [url objectForKey:@"actionType"];
		}
		if ([actionType isEqualToString:@"empty_url"]) {
			self.menuTitle = [menu objectForKey:@"label"];
			selectType = [@"menu" retain];
			selectedIndex = index;
			if (isAppMenu) {
				[[MServerDAO sharedInstance] getMenuOfAppAsync:[menu objectForKey:@"id"]
												   otherParams:otherParams
													  delegate:self];
			} else {
				[[MServerDAO sharedInstance] getSubMenuAsync:[menu objectForKey:@"id"]
												 otherParams:otherParams
													delegate:self];
			}		
		}
		else {
			UINavigationController* navigationController = self.navigationController;
//			if ([MCUserDefaults instance].useLastMenuAsShortKey && [self.menus count] > 1 && !self.isShortcutMore) {
//				MCTabBarController* tabBarController = [[MCTabBarController alloc] init];
//				navigationController = [tabBarController menus:self.menus selectedItem:index];
//				[self.navigationController pushViewController:tabBarController animated:YES];
//				[tabBarController release];
//			}
			[otherParams setObject:[menu objectForKey:@"id"]==nil?@"":[menu objectForKey:@"id"] forKey:@"authValue"];
			[otherParams setObject:@"menu" forKey:@"authKey"];		
			[MCFunction pushViewByUrl:url parameters:otherParams confirmMessage:nil naviController:navigationController];
		}
		
	}
	@catch (NSException * e) {
		[[MCErrorManagement instance] doError:@"99" 
								returnMessage:[NSString stringWithFormat:@"main: Caught %@: %@", [e name], [e reason]]];		
	}	
}

- (BOOL)onSetting:(NSDictionary*)url {
	return NO;
}

//响应按钮事件
-(void)btnPressed:(id)sender{
	UIButton *btn = (UIButton *)sender;
	int row = btn.tag-kTagBase;
	
	[self onMenuPressed:row];
}

- (void)getDataFromServerSuccess: (NSMutableDictionary *)returnValue {
	if ([selectType isEqualToString:@"contactSync"]) {
		NSMutableArray *menu = (NSMutableArray *)returnValue;
		for (NSMutableDictionary *contact in menu) {
			if ([contact objectForKey:@"lbl"]) {
				NSString *label = [[contact objectForKey:@"lbl"] copy];
				[contact setObject:label forKey:@"label"];
				[label release];
				[contact removeObjectForKey:@"lbl"];
			}
		}
		ContactController *contactController = [[ContactController alloc] init];
		contactController.title = @"通讯录";
		contactController.menus = menu;
		contactController.isApp = NO;
		
        [self.navigationController pushViewController:contactController animated:YES];
        [contactController release];
	}else {
		NSMutableArray *menu = [MenuController removeSeqMenu:(NSMutableArray *)returnValue];
		if ([MCUserDefaults instance].useLastMenuAsShortKey && [menu count] > 1 && self.isApp) {
			MCTabBarController* tabBarController = [[MCTabBarController alloc] init];
			tabBarController.title = self.menuTitle;
			tabBarController.tabBarData = [NSDictionary dictionaryWithObjectsAndKeys:menu,@"sct",nil];
			[self.navigationController pushViewController:tabBarController animated:YES];
			[tabBarController release];
			return;
		}
		MenuController *menuViewController = [[MenuController alloc] init];
		menuViewController.title = self.menuTitle;
		menuViewController.menus = menu;
		
		[self.navigationController pushViewController:menuViewController animated:YES];
		[menuViewController release];
	}
	
}

- (void)dealloc {
	[menus release];
	[menusCopy release];
	[menuTitle release];
	[selectType release];
    [super dealloc];
}

#pragma mark ---- 事件处理方法 ----
- (void) logout: (id) sender {
	[self logoutApp];
}

- (void)logoutApp {
	[self messageBox:@"确定重新登录?" //huotianjun注销改为重新登录
			 message:nil
			delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	if (buttonIndex == 1) {
		[[MServerConfigCache sharedInstance] saveCacheToStore];
		[[MServerDAO sharedInstance] logoutAsync];
		
		[self.appDelegate.navController popToRootViewControllerAnimated:YES];
	}
}


#pragma mark ---- 内部方法 ----
+ (NSMutableArray *)removeSeqMenu:(NSMutableArray *)aMenus {
	for(int i = [aMenus count] - 1;i>=0;i--) {
		if ([[[aMenus objectAtIndex:i] objectForKey:@"label"] isEqualToString:@"---"]) {
			[aMenus removeObjectAtIndex:i];
		}
	}	
	return aMenus;
}

@end
